<template>
  <div>
    <div class="crumbs">
      <el-breadcrumb separator="/">
        <el-breadcrumb-item>
          <router-link to="/reporting/competition">竞品上报</router-link>
        </el-breadcrumb-item>
        <el-breadcrumb-item>新增竞品上报</el-breadcrumb-item>
      </el-breadcrumb>
    </div>
    <basic-container>
      <el-form :model="categoryForm" label-width="120px" label-position="right">
        <el-row>
          <el-col :span="8">
            <el-form-item label="客户" required>
              <select-customer-form
                :customerObj="{customerName: categoryForm.customerName, customerSn: categoryForm.customerSn}"
                @changeCustomer="handleSelectCustomer"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="上报人员" required>
              <el-select
                filterable
                class="fill-width"
                v-model="categoryForm.reportManId"
                style="float: left"
                placeholder="请选择"
              >
                <el-option
                  v-for="item in teamList"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="上报位置定位" required>
              <p style="text-align: left">{{reportLocation.formattedAddress}}</p>
              <avue-map v-model="reportLocation" style="width:200px" :lnglat="lnglat"></avue-map>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="上报日期" required>
              <el-date-picker
                class="fill-width"
                v-model="categoryForm.reportDate"
                format="yyyy-MM-dd"
                value-format="yyyy-MM-dd"
                type="date"
                placeholder="选择日期"
              ></el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="备注" required>
              <el-input
                type="textarea"
                :maxlength="255"
                v-model="categoryForm.remarks"
                style="float: left"
                placeholder="请输入"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="竞品名称" required>
              <el-input
                class="fill-width"
                v-model="categoryForm.goodsName"
                style="float: left"
                placeholder="请输入"
                :precision="2"
                @change="countPrice"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="竞品单位" required>
              <el-input
                class="fill-width"
                v-model="categoryForm.goodsUnit"
                style="float: left"
                placeholder="请输入"
                :precision="2"
                @change="countPrice"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="竞品数量">
              <el-input-number
                class="fill-width"
                v-model="categoryForm.goodsNum"
                style="float: left"
                placeholder="请输入"
                :precision="2"
              ></el-input-number>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="竞品价格">
              <el-input-number
                class="fill-width"
                v-model="categoryForm.tradePrice"
                style="float: left"
                placeholder="请输入"
                :precision="2"
              ></el-input-number>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="24">
            <el-form-item label="上报图片" required>
              <div
                v-if="categoryForm.photoList"
                class="thumbUrl"
                v-for="(item,index) in categoryForm.photoList"
              >
                <img :src="item.picUrl" />
                <div class="hover_show">
                  <i class="el-icon-delete" @click="handlePictureRemove(index)"></i>
                </div>
              </div>
              <div class="select_img" @click="sel_img()" style="float: left;">
                <i class="el-icon-plus"></i>
              </div>
              <div v-if="sleImg">
                <el-dialog title="选择图片" :visible.sync="sleImg" style="text-align: left;">
                  <sel-img-photogallery ref="selImg" type="11" @select="onSelectImgs"></sel-img-photogallery>
                </el-dialog>
              </div>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item>
          <div>
            <el-button type="primary" size="medium" @click="save">保存</el-button>
            <el-button type="default" size="medium" @click="close">取消</el-button>
          </div>
        </el-form-item>
        <el-dialog title="选择商品" :visible.sync="dialogVisible">
          <goods-list @select="onSelectGoods"></goods-list>
        </el-dialog>
      </el-form>
    </basic-container>
  </div>
</template>

<script>
import Request from "../../order_con/request.js";
import { getStore, setStore } from "@/util/store";
import selImgPhotogallery from "@/components/pds/common/sel_img_photogallery";
import { fetchList } from "@/api/crm/customer";
import { fetchList as teamList } from "@/api/crm/marketemployee"; //联系人
import { addCompetition } from "@/api/crm/competition";
import AvueMap from "avue-plugin-map";
import { mapGetters } from "vuex";
import Vue from "vue";
import { fetchDict } from "@/util/util";
import goodsList from "../../order_con/customerOrder/components/goodsList.vue";
import moment from "moment";
import selectCustomerForm from "@/components/crm/select_customer_form";
export default {
  data() {
    return {
      request: new Request(),
      categoryForm: {
        photoList: [],
        totalAmount: 0,
        otherAmount: 0,
        // couponAmount: 0,
        goodsTotalAmount: 0
      },
      goodsTypeList: [
        {
          label: "普通",
          value: "1"
        },
        {
          label: "促销品",
          value: "2"
        },
        {
          label: "赠品",
          value: "3"
        }
      ],
      sleImg: false,
      //初始化坐标
      lnglat: {
        P: 29.563761,
        R: 106.55046400000003
      },
      custmoerList: [],
      teamList: [],
      visit_step: [],
      customer_status: [],
      visit_status: [],
      data_report_status: [],
      reportLocation: {
        formattedAddress: "",
        longitude: "",
        latitude: ""
      },
      loading: false,
      selectGoods: {
        goodsName: "",
        loading: "",
        goodsList: [],
        goodsId: "",
        goodsModelList: []
      },
      tableData: [],
      dialogVisible: false
    };
  },
  components: {
    selImgPhotogallery,
    goodsList,
    selectCustomerForm
  },
  computed: {
    ...mapGetters(["tagWel", "tagList", "tag", "website"]),
    tagLen() {
      return this.tagList.length || 0;
    }
  },
  mounted() {},
  created() {
    fetchDict("scm_visit_step", this.visit_step);
    fetchDict("scm_customer_status", this.customer_status);
    fetchDict("scm_visit_status", this.visit_status);
    fetchDict("scm_data_report_status", this.data_report_status);
    Vue.use(AvueMap);
    this.getList();
  },
  methods: {
    //获取销售区域
    getList(page, params) {
      this.tableLoading = true;
      fetchList({ current: 1, size: 1000 }).then(response => {
        this.custmoerList = response.data.data.records;
      });
      teamList({ current: 1, size: 1000 }).then(response => {
        this.teamList = response.data.data.records;
      });
    },
    async remoteStaffList(name) {
      let query = {};
      if (name) query.name = name;
      let res = await teamList(Object.assign(query, { current: 1, size: 50 }));
      this.teamList = res.data.data.records;
    },
    async handleSelectCustomer(customerObj) {
      if (this.categoryForm.customerSn === customerObj.customerSn) return;
      this.$set(this.categoryForm, "customerSn", customerObj.customerSn);
      this.$set(this.categoryForm, "customerName", customerObj.customerName);
    },
    changeModel(modelName, row) {
      this.$set(row, "tradePrice", getPrice(modelName, row.goodsModelList));
      this.$set(row, "commonPrice", getPrice(modelName, row.goodsModelList));
      this.countPrice();
    },
    sel_img() {
      this.sleImg = true;
    },
    onSelectImgs(imgs) {
      console.log(imgs, imgs.length);
      if (this.categoryForm.photoList.length+imgs.length > 5) {
        this.sleImg = false;
        this.$message.success("最多添加5张图片");
        return;
      }
      // return;
      imgs.forEach(item => {
        this.categoryForm.photoList.push({ id: item.id, picUrl: item.picUrl });
      });
      this.sleImg = false;
    },
    // 删除el-upload的图片
    handlePictureRemove(index) {
      this.categoryForm.photoList.splice(index, 1);
    },
    showGoodsDialog($event, index) {
      this.dialogVisible = true;
      this.selectedRowIndex = index;
    },
    onGoodsSelectChange(e, row) {
      if (e) {
        let selectedGoods = row.goodsList.filter(item => item.id === e)[0];
        row.goodsModelList = selectedGoods.goodsModelList;
        this.$set(row, "goodsName", selectedGoods.goodsName);
        this.$set(row, "thumbUrl", selectedGoods.thumbUrl);
      } else {
        // 清空选项时
        this.$set(row, "goodsId", "");
        row.goodsId = "";
      }
    },
    onSelectGoods(goods) {
      this.dialogVisible = false;
      // this.selectGoods = goods;
      this.addSubmit(goods);
    },
    // 商品选择相关
    searchGoodsByName(row) {
      // 将row信息传入
      let _this = this;
      return function(searchValue) {
        if (searchValue !== "") {
          row.loading = true;
          console.log("time", searchValue);
          let params = {
            goodsName: searchValue
          };
          params.shopId = getStore({ name: "shopId" });
          params.pageNo = _this.currentPage;
          params.pageSize = _this.pageSize;
          params.goodsName = searchValue;
          _this.request.getGoodsList(params).then(res => {
            if (res.code == 200) {
              _this.$set(row, "goodsList", res.ext.list);
              _this.$set(row, "loading", false);
              _this.goodsList = res.ext.list;
              _this.currentPage = res.ext.pageNo;
              _this.totalCount = res.ext.count;
            } else if (res.code == "983") {
              _this.goodsList = [];
            } else {
              _this.$message.error("请求失败");
            }
          });
        }
      };
    },
    addSubmit(goods) {
      console.log(goods);

      goods.goodsModelList = goods.goodsModelList.map(item => {
        item["modelId"] = item.id;
        return item;
      });
      var good = {
        salesGoodsType: "1",
        goodsId: goods.goodsModelList[0].goodsId,
        goodsImg: goods.thumbUrl,
        goodsName: goods.goodsName,
        unit: goods.goodsModelList[0].modelUnit,
        goodsModelList: goods.goodsModelList,
        modelName: goods.goodsModelList[0].modelName,
        goodsNum: 1,
        remarks: "",
        commonPrice: goods.goodsModelList[0].modelPrice,
        tradePrice: goods.goodsModelList[0].modelPrice,
        goodsModelId: goods.goodsModelList[0].id,
        expiration: "一个月",
        productTime: moment()
          .startOf("day")
          .format("YYYY-MM-DD HH:mm:ss"),
        maturityTime: moment()
          .startOf("day")
          .add(30, "day")
          .format("YYYY-MM-DD HH:mm:ss")
      };
      this.tableData.push(good);
      this.countPrice();
    },
    delGood(index) {
      this.tableData.splice(index, 1);
      this.countPrice();
    },
    countPrice() {
      this.$set(this.categoryForm, "totalAmount", this.getTotalAmount());
      // this.countCouponAmount();
    },
    getTotalAmount() {
      let totalAmount = 0;
      this.tableData &&
        this.tableData.length &&
        this.tableData.map(item => {
          if (item.salesGoodsType === "1")
            totalAmount += parseFloat(item.goodsNum * item.commonPrice);
          if (item.salesGoodsType === "2")
            totalAmount += parseFloat(item.goodsNum * item.tradePrice);
        });
      this.$set(this.categoryForm, "goodsTotalAmount", totalAmount);
      totalAmount += this.categoryForm.otherAmount;
      return totalAmount;
    },
    // 计算优惠价格
    // countCouponAmount() {
    //   let couponAmount = this.getTotalAmount() - this.categoryForm.totalAmount;
    //   this.$set(this.categoryForm, 'couponAmount', couponAmount);
    // },
    //确定
    save() {
      let tmp = [];
      this.categoryForm.photoList.forEach(item => {
        tmp.push(item.id);
      });
      this.categoryForm.photoList = tmp;
      let params = this.categoryForm;
      params.reportAddress = this.reportLocation.formattedAddress;
      params.reportLocation =
        this.reportLocation.longitude && this.reportLocation.latitude
          ? this.reportLocation.longitude + "," + this.reportLocation.latitude
          : "";
      // let detailList = [];
      this.tableData.forEach(item => {
        let tradePrice = 0;
        if (item.salesGoodsType === "1") tradePrice = item.commonPrice;
        if (item.salesGoodsType === "2") tradePrice = item.tradePrice;
        // detailList.push({
        //   salesGoodsType: item.salesGoodsType,
        //   goodsModelId:item.goodsModelId,
        //   tradePrice: tradePrice,
        //   goodsNum:item.goodsNum,
        //   expiration:item.expiration,
        //   productTime:item.productTime,
        //   maturityTime:item.maturityTime,
        //   remarks:item.remarks
        // });
      });
      // params.detailList = detailList;
      addCompetition(params).then(response => {
        if (response.data.code == 0) {
          this.$message.success("创建成功");
          let _this = this;
          setTimeout(function() {
            _this.close();
          }, 2000);
        } else {
          this.$message.success(response.data.msg);
        }
      });
    },
    close() {
      var str_before = location.href.split("#")[1];
      let { tag, key } = this.findTag(str_before);
      this.$store.commit("DEL_TAG", tag);
      this.$router.go(-1);
    },
    findTag(value) {
      let tag, key;
      this.tagList.map((item, index) => {
        if (item.value === value) {
          tag = item;
          key = index;
        }
      });
      return { tag: tag, key: key };
    }
  }
};

function getPrice(modelId, data) {
  let price = 0;
  data.map(item => {
    if (item.modelId === modelId) return (price = item.modelPrice);
  });
  return price;
}
</script>

<style scoped lang="scss">
.crumbs {
  margin: 20px 10px;
}
.thumbUrl {
  width: 150px;
  height: 150px;
  position: relative;
  line-height: 146px;
  float: left;
  margin-right: 15px;
  border-radius: 6px;
  overflow: hidden;
  border: 1px solid #c0ccda;
  text-align: center;
}
.thumbUrl img {
  width: 100%;
  height: 100%;
}
.thumbUrl .hover_show {
  position: absolute;
  top: 0;
  left: 0;
  background-color: rgba(0, 0, 0, 0.5);
  width: 100%;
  height: 100%;
  display: none;
}
.thumbUrl:hover .hover_show {
  display: block;
}
.thumbUrl .hover_show i {
  color: #fff;
  margin: 0 10px;
  cursor: pointer;
}
.select_img {
  width: 148px;
  height: 148px;
  line-height: 146px;
  border: 1px dashed #c0ccda;
  background-color: #fbfdff;
  font-size: 28px;
  color: #8c939d;
  cursor: pointer;
  border-radius: 6px;
  text-align: center;
}
</style>
